<template>
  <el-dialog :title="'导入题库'" :close-on-click-modal="false" :visible.sync="visible">
    <el-row>
      <div class="el-form-item__content">
        <el-upload ref="upload" action="#" multiple="false" :auto-upload="false" :file-list="fileList"
          :http-request="uploadHttpRequest">
          <el-button size="small" type="primary">选择文件</el-button>
          <div slot="tip" class="el-upload__tip">一次只能上传一个xls/xlsx文件，且不超过10M</div>
        </el-upload>
        <el-button type="primary" size="small" @click="submitUpload">上 传</el-button>
        <a type="primary" href="http://localhost:8888/api/question/question/download?fileName=test.xls" size="small">下载导入模板</a>
      </div>
    </el-row>
  </el-dialog>
</template>
<script>
export default {
  data () {
    return {
      visible: false,
      fileList: []
    }
  },
  methods: {
    // 初始化方法
    init () {
      this.visible = true // 文件显示内容栏
    },
    // 实现文件上传
    uploadHttpRequest (param) {
      // 构建上传的表单
      const formData = new FormData() // FormData对象，添加参数只能通过append('key', value)的形式添加
      formData.append('file', param.file) // 添加文件对象
      formData.append('uploadType', this.rulesType)
      // 发送请求
      this.$http({
        url: this.$http.adornUrl(`/question/question/upload`),
        method: 'post',
        data: formData,
        contentType: 'form' // 内容类型：表单类型
      }).then(res => {
        const { data: { code, num, msg } } = res
        if (code === 0) {
          this.fileList = []
          this.visible = false
          this.$message({
            message: '上传文件成功,导入条数:' + num,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        } else { // 返回的状态码异常
          this.$message.error(msg)
        }
      })
        .catch(err => { // 上传过程中的出现异常
          console.log('失败', err)
          param.onError()
        })
    },
    submitUpload () {
      // 通过$refs内容对象，获取其他表单元素的并执行提交
      this.$refs.upload.submit()
    }
  }
}
</script>
